{% extends "base.html" %}
{% block title %}规范性分析 - {{ app_name }}{% endblock %}

{% block extra_css %}
<!-- 引入统一设计系统 -->
<link rel="stylesheet" href="/static/css/design-system/index.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.0/chart.min.css">
<style>
    /* 规范性分析特定样式 */
    :root {
        --compliance-primary: #f59e0b;
        --compliance-primary-light: #fef3c7;
        --compliance-primary-dark: #d97706;
        --compliance-success: #10b981;
        --compliance-success-light: #d1fae5;
        --compliance-error: #ef4444;
        --compliance-error-light: #fee2e2;
        --compliance-warning: #f59e0b;
        --compliance-warning-light: #fef3c7;
    }

    .compliance-header {
        background: linear-gradient(135deg, var(--compliance-primary-dark) 0%, var(--compliance-primary) 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }

    .stat-card-custom {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        border-left: 4px solid var(--compliance-primary);
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .stat-card-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .stat-value {
        font-size: 2.5rem;
        font-weight: 700;
        color: var(--color-text-primary);
        margin-bottom: 0.5rem;
    }

    .stat-label {
        font-size: 0.875rem;
        color: var(--color-text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .tab-container {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    }

    .custom-tabs {
        display: flex;
        background: var(--color-bg-tertiary);
        border-bottom: 1px solid var(--color-border-primary);
        flex-wrap: wrap;
    }

    .custom-tab {
        padding: 1rem 1.5rem;
        cursor: pointer;
        border: none;
        background: none;
        color: var(--color-text-secondary);
        font-weight: 500;
        transition: all 0.2s;
        position: relative;
        flex: 1;
        min-width: 120px;
        text-align: center;
    }

    .custom-tab:hover {
        color: var(--compliance-primary);
        background: var(--color-bg-secondary);
    }

    .custom-tab.active {
        color: var(--compliance-primary);
        background: white;
    }

    .custom-tab.active::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--compliance-primary);
    }

    .tab-content-custom {
        padding: 2rem;
        min-height: 500px;
    }

    .compliance-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 1rem;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .compliance-badge.compliant {
        background: var(--compliance-success-light);
        color: var(--compliance-success);
    }

    .compliance-badge.non-compliant {
        background: var(--compliance-error-light);
        color: var(--compliance-error);
    }

    .compliance-badge.partial {
        background: var(--compliance-warning-light);
        color: var(--compliance-warning);
    }

    .compliance-item {
        padding: 1rem;
        border-bottom: 1px solid var(--color-border-secondary);
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: background 0.2s;
    }

    .compliance-item:hover {
        background: var(--color-bg-secondary);
    }

    .compliance-item:last-child {
        border-bottom: none;
    }

    .compliance-name {
        font-weight: 500;
        color: var(--color-text-primary);
    }

    .compliance-metrics {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .compliance-rate {
        font-size: 0.875rem;
        font-weight: 600;
        padding: 0.25rem 0.5rem;
        border-radius: 0.5rem;
        background: var(--color-bg-tertiary);
    }

    .compliance-rate.high {
        background: var(--compliance-success-light);
        color: var(--compliance-success);
    }

    .compliance-rate.medium {
        background: var(--compliance-warning-light);
        color: var(--compliance-warning);
    }

    .compliance-rate.low {
        background: var(--compliance-error-light);
        color: var(--compliance-error);
    }

    .detail-card {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border-left: 4px solid var(--color-border-primary);
    }

    .detail-card.compliant {
        border-left-color: var(--compliance-success);
    }

    .detail-card.non-compliant {
        border-left-color: var(--compliance-error);
    }

    .detail-card.partial {
        border-left-color: var(--compliance-warning);
    }

    .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }

    .detail-title {
        font-weight: 600;
        color: var(--color-text-primary);
    }

    .detail-meta {
        display: flex;
        gap: 1rem;
        font-size: 0.875rem;
        color: var(--color-text-secondary);
    }

    .detail-content {
        color: var(--color-text-secondary);
        line-height: 1.6;
    }

    .detail-section {
        margin-bottom: 0.75rem;
    }

    .detail-label {
        font-weight: 500;
        color: var(--color-text-primary);
        margin-bottom: 0.25rem;
    }

    .confidence-indicator {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.25rem 0.5rem;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .confidence-indicator.high {
        background: var(--compliance-success-light);
        color: var(--compliance-success);
    }

    .confidence-indicator.medium {
        background: var(--compliance-warning-light);
        color: var(--compliance-warning);
    }

    .confidence-indicator.low {
        background: var(--compliance-error-light);
        color: var(--compliance-error);
    }

    .empty-state {
        text-align: center;
        padding: 3rem;
        color: var(--color-text-secondary);
    }

    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    .chart-legend {
        display: flex;
        justify-content: center;
        gap: 1rem;
        margin-top: 1rem;
        flex-wrap: wrap;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.875rem;
    }

    .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 50%;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .compliance-header {
            padding: 1.5rem 0;
        }

        .stat-value {
            font-size: 2rem;
        }

        .custom-tabs {
            flex-direction: column;
        }

        .custom-tab {
            flex: none;
            text-align: left;
        }

        .tab-content-custom {
            padding: 1rem;
        }

        .detail-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 0.5rem;
        }

        .detail-meta {
            flex-direction: column;
            gap: 0.5rem;
        }
    }

    /* 加载动画 */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s, visibility 0.3s;
    }

    .loading-overlay.active {
        opacity: 1;
        visibility: visible;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid rgba(255, 255, 255, 0.3);
        border-top: 4px solid white;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* 错误状态 */
    .error-state {
        text-align: center;
        padding: 3rem;
        color: var(--color-error);
    }

    .error-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
    }

    /* 图表容器 */
    .chart-wrapper {
        position: relative;
        height: 400px;
        margin-bottom: 1rem;
    }

    .chart-actions {
        position: absolute;
        top: 1rem;
        right: 1rem;
        display: flex;
        gap: 0.5rem;
        z-index: 10;
    }

    .chart-action {
        background: white;
        border: 1px solid var(--color-border-primary);
        border-radius: 0.375rem;
        padding: 0.5rem;
        cursor: pointer;
        transition: all 0.2s;
        color: var(--color-text-secondary);
    }

    .chart-action:hover {
        background: var(--color-bg-secondary);
        color: var(--color-text-primary);
    }

    /* 进度条 */
    .progress-custom {
        width: 100%;
        height: 8px;
        background: var(--color-bg-tertiary);
        border-radius: 4px;
        overflow: hidden;
    }

    .progress-bar-custom {
        height: 100%;
        background: var(--compliance-primary);
        border-radius: 4px;
        transition: width 0.3s;
    }

    .progress-bar-custom.success {
        background: var(--compliance-success);
    }

    .progress-bar-custom.error {
        background: var(--compliance-error);
    }

    .progress-bar-custom.warning {
        background: var(--compliance-warning);
    }

    /* 筛选面板 */
    .filter-section {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .filter-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: var(--color-text-primary);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .filter-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .filter-label {
        font-size: 0.875rem;
        font-weight: 500;
        color: var(--color-text-secondary);
    }

    .filter-input {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border-primary);
        border-radius: 0.5rem;
        font-size: 0.875rem;
        transition: border-color 0.2s;
    }

    .filter-input:focus {
        outline: none;
        border-color: var(--compliance-primary);
        box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
    }

    .filter-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 1rem;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .compliance-trend {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .trend-up {
        color: var(--compliance-success);
    }

    .trend-down {
        color: var(--compliance-error);
    }

    .trend-neutral {
        color: var(--color-text-secondary);
    }
</style>
{% endblock %}

{% block content %}
<!-- 页面头部 -->
<div class="compliance-header">
    <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="mb-4 md:mb-0">
                <h1 class="text-3xl font-bold mb-2">
                    <i class="fas fa-shield-alt mr-2"></i>规范性分析
                </h1>
                <p class="opacity-90">分析信访答复的规范性和合规性情况，确保服务质量</p>
            </div>
            <div class="flex items-center gap-3">
                <div class="text-center">
                    <div class="text-2xl font-semibold mb-0" id="lastUpdate">-</div>
                    <small>最后更新</small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 主要内容 -->
<div class="container mx-auto px-4 my-4">
    <!-- 筛选面板 -->
    <div class="filter-section">
        <div class="filter-title">
            <i class="fas fa-filter"></i>分析筛选
        </div>
        <div class="filter-row">
            <div class="filter-group">
                <label class="filter-label">分析任务</label>
                <select class="filter-input" id="taskSelect">
                    <option value="">全部任务</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">开始日期</label>
                <input type="date" class="filter-input" id="startDate">
            </div>
            <div class="filter-group">
                <label class="filter-label">结束日期</label>
                <input type="date" class="filter-input" id="endDate">
            </div>
            <div class="filter-group">
                <label class="filter-label">合规状态</label>
                <select class="filter-input" id="complianceStatus">
                    <option value="">全部状态</option>
                    <option value="compliant">合规</option>
                    <option value="non_compliant">不合规</option>
                    <option value="partial">部分合规</option>
                </select>
            </div>
        </div>
        <div class="filter-row">
            <div class="filter-group">
                <label class="filter-label">规范性类型</label>
                <input type="text" class="filter-input" id="complianceType" placeholder="输入规范性类型（可选）">
            </div>
            <div class="filter-group">
                <label class="filter-label">问题类别</label>
                <input type="text" class="filter-input" id="issueCategory" placeholder="输入问题类别（可选）">
            </div>
            <div class="filter-group">
                <label class="filter-label">最低置信度</label>
                <input type="number" class="filter-input" id="minConfidence" placeholder="0.0 - 1.0" step="0.1" min="0" max="1">
            </div>
        </div>
        <div class="filter-actions">
            <button class="btn btn-secondary" onclick="resetFilters()">
                <i class="fas fa-redo me-1"></i>重置
            </button>
            <button class="btn btn-primary" onclick="loadAnalysis()">
                <i class="fas fa-search me-1"></i>开始分析
            </button>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8" id="statsGrid">
        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-value" id="totalRecords">-</div>
                    <div class="stat-label">总记录数</div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-green-400 to-green-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-file-alt text-white text-xl"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="totalTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-value" id="complianceRate">-</div>
                    <div class="stat-label">合规率</div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-amber-400 to-amber-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-percentage text-white text-xl"></i>
                </div>
            </div>
            <div class="progress-custom mt-2">
                <div class="progress-bar-custom" id="complianceProgress" style="width: 0%"></div>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-value" id="avgConfidence">-</div>
                    <div class="stat-label">平均置信度</div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-blue-400 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-brain text-white text-xl"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="confidenceTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-value" id="totalIssues">-</div>
                    <div class="stat-label">问题类型数</div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-red-400 to-red-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-exclamation-triangle text-white text-xl"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="issuesTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>
    </div>

    <!-- 分析标签页 -->
    <div class="tab-container">
        <div class="custom-tabs">
            <button class="custom-tab active" data-tab="distribution">
                <i class="fas fa-chart-pie me-1"></i>合规性分布
            </button>
            <button class="custom-tab" data-tab="types">
                <i class="fas fa-list me-1"></i>规范性类型
            </button>
            <button class="custom-tab" data-tab="issues">
                <i class="fas fa-bug me-1"></i>问题类别
            </button>
            <button class="custom-tab" data-tab="confidence">
                <i class="fas fa-tachometer-alt me-1"></i>置信度分析
            </button>
            <button class="custom-tab" data-tab="details">
                <i class="fas fa-file-text me-1"></i>规范性详情
            </button>
        </div>

        <div class="tab-content-custom">
            <!-- 合规性分布 -->
            <div id="distribution" class="tab-pane">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="lg:col-span-2">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('complianceDistribution')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('complianceDistribution')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="complianceDistributionChart"></canvas>
                        </div>
                        <div class="chart-legend" id="complianceLegend"></div>
                    </div>
                    <div class="space-y-4">
                        <h5 class="font-semibold mb-3">合规性构成</h5>
                        <div id="complianceBreakdown"></div>

                        <h5 class="font-semibold mb-3">规范性指标</h5>
                        <div id="complianceMetrics"></div>
                    </div>
                </div>
            </div>

            <!-- 规范性类型 -->
            <div id="types" class="tab-pane" style="display: none;">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="lg:col-span-2">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('complianceTypes')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('complianceTypes')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="complianceTypesChart"></canvas>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <h5 class="font-semibold mb-3">类型排行</h5>
                        <div id="complianceTypesRanking"></div>

                        <h5 class="font-semibold mb-3">合规率分布</h5>
                        <div id="complianceRateDistribution"></div>
                    </div>
                </div>
            </div>

            <!-- 问题类别 -->
            <div id="issues" class="tab-pane" style="display: none;">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="lg:col-span-2">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('issueCategories')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('issueCategories')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="issueCategoriesChart"></canvas>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <h5 class="font-semibold mb-3">问题严重程度</h5>
                        <div id="issueSeverity"></div>

                        <h5 class="font-semibold mb-3">高频问题</h5>
                        <div id="frequentIssues"></div>
                    </div>
                </div>
            </div>

            <!-- 置信度分析 -->
            <div id="confidence" class="tab-pane" style="display: none;">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('confidenceStats')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('confidenceStats')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="confidenceStatsChart"></canvas>
                        </div>
                    </div>
                    <div>
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('confidenceDistribution')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('confidenceDistribution')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="confidenceDistributionChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="mt-6">
                    <h5 class="font-semibold mb-3">置信度分析</h5>
                    <div id="confidenceAnalysis"></div>
                </div>
            </div>

            <!-- 规范性详情 -->
            <div id="details" class="tab-pane" style="display: none;">
                <div>
                    <div class="flex justify-between items-center mb-4">
                        <h5 class="font-semibold mb-0">规范性详情</h5>
                        <div class="flex gap-2">
                            <button class="px-3 py-1 border border-primary text-primary rounded hover:bg-primary hover:text-white transition-colors" onclick="exportDetails()">
                                <i class="fas fa-file-export mr-1"></i>导出
                            </button>
                            <button class="px-3 py-1 border border-secondary text-secondary rounded hover:bg-secondary hover:text-white transition-colors" onclick="refreshDetails()">
                                <i class="fas fa-refresh mr-1"></i>刷新
                            </button>
                        </div>
                    </div>
                    <div id="complianceDetails"></div>

                    <!-- 分页控件 -->
                    <div class="flex justify-between items-center mt-4">
                        <div class="text-muted" id="detailsInfo"></div>
                        <div class="flex gap-2" id="detailsPagination"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<!-- 通用模态框 -->
<div class="modal fade" id="commonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">标题</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modalBody">
                内容
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="modalConfirm">确定</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 引入必要的库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.0/chart.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

<!-- 引入组件库 -->
<script src="/static/js/components/base/BaseComponent.js"></script>
<script src="/static/js/components/base/StatCard.js"></script>
<script src="/static/js/components/base/FilterPanel.js"></script>
<script src="/static/js/components/base/ChartContainer.js"></script>

<!-- 引入工具类 -->
<script src="/static/js/utils/ApiClient.js"></script>
<script src="/static/js/utils/CacheManager.js"></script>
<script src="/static/js/utils/ErrorHandler.js"></script>

<script>
// 全局变量
let apiClient;
let cacheManager;
let errorHandler;
let charts = {};
let currentData = null;
let currentPage = 1;
let pageSize = 10;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
async function initializeApp() {
    try {
        // 初始化工具类
        apiClient = new ApiClient({
            baseUrl: '/api',
            timeout: 30000,
            refreshToken: refreshToken
        });

        cacheManager = new CacheManager({
            prefix: 'compliance-analysis',
            ttl: 300000 // 5分钟缓存
        });

        errorHandler = new ErrorHandler({
            enableLogging: true,
            enableNotification: true,
            enableReporting: false
        });

        // 设置全局错误处理
        window.addEventListener('error', (event) => {
            errorHandler.handleError(event.error, '全局错误');
        });

        window.addEventListener('unhandledrejection', (event) => {
            errorHandler.handleError(event.reason, '未处理的Promise拒绝');
        });

        // 初始化页面
        await initializePage();

        console.log('规范性分析页面初始化完成');
    } catch (error) {
        console.error('应用初始化失败:', error);
        errorHandler.handleError(error, '应用初始化');
    }
}

// 初始化页面
async function initializePage() {
    try {
        // 设置默认日期
        setDefaultDates();

        // 加载分析任务
        await loadTasks();

        // 初始化图表
        initializeCharts();

        // 绑定事件
        bindEvents();

        // 加载默认数据
        await loadDefaultData();

        // 更新最后更新时间
        updateLastUpdateTime();
    } catch (error) {
        console.error('页面初始化失败:', error);
        errorHandler.handleError(error, '页面初始化');
    }
}

// 设置默认日期
function setDefaultDates() {
    const today = new Date();
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);

    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    document.getElementById('startDate').value = thirtyDaysAgo.toISOString().split('T')[0];
}

// 加载分析任务
async function loadTasks() {
    try {
        const cacheKey = 'analysis-tasks';
        const cachedData = cacheManager.get(cacheKey);

        if (cachedData) {
            populateTaskSelect(cachedData);
            return;
        }

        const response = await apiClient.get('/analysis-tasks', {
            params: {
                status: 'completed',
                limit: 100
            }
        });

        if (response.success) {
            const tasks = response.data.tasks || response.data.items || response.data || [];
            cacheManager.set(cacheKey, tasks, 600000); // 10分钟缓存
            populateTaskSelect(tasks);
        }
    } catch (error) {
        console.error('加载任务失败:', error);
        errorHandler.handleError(error, '加载分析任务');
    }
}

// 填充任务选择框
function populateTaskSelect(tasks) {
    const taskSelect = document.getElementById('taskSelect');
    taskSelect.innerHTML = '<option value="">全部任务</option>';

    tasks.forEach(task => {
        const option = document.createElement('option');
        option.value = task.id;
        option.textContent = task.name || `任务 ${task.id}`;
        taskSelect.appendChild(option);
    });
}

// 初始化图表
function initializeCharts() {
    // 合规性分布图表
    charts.complianceDistribution = new Chart(
        document.getElementById('complianceDistributionChart'),
        {
            type: 'doughnut',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: [],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '合规性分布'
                    }
                }
            }
        }
    );

    // 规范性类型图表
    charts.complianceTypes = new Chart(
        document.getElementById('complianceTypesChart'),
        {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '合规率',
                    data: [],
                    backgroundColor: []
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '规范性类型合规率'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        }
    );

    // 问题类别图表
    charts.issueCategories = new Chart(
        document.getElementById('issueCategoriesChart'),
        {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '严重程度',
                    data: [],
                    backgroundColor: []
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '问题类别严重程度'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        }
    );

    // 置信度统计图表
    charts.confidenceStats = new Chart(
        document.getElementById('confidenceStatsChart'),
        {
            type: 'bar',
            data: {
                labels: ['平均置信度', '最低置信度', '最高置信度'],
                datasets: [{
                    label: '置信度',
                    data: [],
                    backgroundColor: ['#10b981', '#ef4444', '#3b82f6']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '置信度统计'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 1
                    }
                }
            }
        }
    );

    // 置信度分布图表
    charts.confidenceDistribution = new Chart(
        document.getElementById('confidenceDistributionChart'),
        {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '数量',
                    data: [],
                    borderColor: '#f59e0b',
                    backgroundColor: 'rgba(245, 158, 11, 0.1)',
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '置信度分布'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        }
    );
}

// 绑定事件
function bindEvents() {
    // 标签页切换
    document.querySelectorAll('.custom-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            switchTab(this.dataset.tab);
        });
    });

    // 监听筛选条件变化
    const filterInputs = ['taskSelect', 'startDate', 'endDate', 'complianceStatus', 'complianceType', 'issueCategory', 'minConfidence'];
    filterInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('change', debounceFilter);
            if (element.type === 'text' || element.type === 'number') {
                element.addEventListener('input', debounceFilter);
            }
        }
    });

    // 窗口大小改变时重新调整图表
    window.addEventListener('resize', debounce(() => {
        Object.values(charts).forEach(chart => {
            if (chart.resize) chart.resize();
        });
    }, 250));
}

// 防抖函数
function debounce(func, wait = 300) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 防抖筛选
const debounceFilter = debounce(() => {
    if (currentData) {
        loadAnalysis();
    }
}, 500);

// 加载默认数据
async function loadDefaultData() {
    try {
        await loadAnalysis();
    } catch (error) {
        console.error('加载默认数据失败:', error);
        showEmptyState('加载失败，请重试');
    }
}

// 加载分析数据
async function loadAnalysis() {
    showLoading(true);

    try {
        const filters = getFilters();
        const cacheKey = `compliance-analysis-${JSON.stringify(filters)}`;
        const cachedData = cacheManager.get(cacheKey);

        if (cachedData) {
            currentData = cachedData;
            updateDashboard(cachedData);
            updateAllCharts(cachedData);
            updateLastUpdateTime();
            showLoading(false);
            return;
        }

        const response = await apiClient.post('/compliance-analysis/analyze', filters);

        if (response.success) {
            currentData = response.data;
            cacheManager.set(cacheKey, response.data, 300000); // 5分钟缓存
            updateDashboard(response.data);
            updateAllCharts(response.data);
            updateLastUpdateTime();
        } else {
            throw new Error(response.message || '分析失败');
        }
    } catch (error) {
        console.error('分析失败:', error);
        errorHandler.handleError(error, '加载分析数据');
        showError('分析失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 获取筛选条件
function getFilters() {
    return {
        task_id: document.getElementById('taskSelect').value ? parseInt(document.getElementById('taskSelect').value) : null,
        start_date: document.getElementById('startDate').value || null,
        end_date: document.getElementById('endDate').value || null,
        compliance_status: document.getElementById('complianceStatus').value || null,
        compliance_type: document.getElementById('complianceType').value || null,
        issue_category: document.getElementById('issueCategory').value || null,
        min_confidence: document.getElementById('minConfidence').value ? parseFloat(document.getElementById('minConfidence').value) : null
    };
}

// 更新仪表板
function updateDashboard(data) {
    if (!data || !data.analysis_metadata) return;

    const metadata = data.analysis_metadata;

    // 更新统计卡片
    document.getElementById('totalRecords').textContent = (metadata.total_records || 0).toLocaleString();
    document.getElementById('complianceRate').textContent = (metadata.compliance_rate || 0).toFixed(1) + '%';
    document.getElementById('avgConfidence').textContent = (metadata.average_confidence || 0).toFixed(3);
    document.getElementById('totalIssues').textContent = Object.keys(data.issue_category_analysis?.category_analysis || {}).length;

    // 更新进度条
    const complianceProgress = document.getElementById('complianceProgress');
    complianceProgress.style.width = (metadata.compliance_rate || 0) + '%';

    // 更新趋势指示器
    updateTrendIndicators(metadata);
}

// 更新趋势指示器
function updateTrendIndicators(metadata) {
    // 这里可以根据实际数据计算趋势
    // 暂时显示中性趋势
    const trendElements = ['totalTrend', 'confidenceTrend', 'issuesTrend'];
    trendElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.innerHTML = '<i class="fas fa-minus"></i><span>较上期</span>';
            element.className = 'compliance-trend mt-2 trend-neutral';
        }
    });
}

// 更新所有图表
function updateAllCharts(data) {
    updateComplianceDistributionChart(data.compliance_distribution);
    updateComplianceTypesChart(data.compliance_type_analysis);
    updateIssueCategoriesChart(data.issue_category_analysis);
    updateConfidenceCharts(data.confidence_analysis);
    updateComplianceBreakdown(data.compliance_distribution);
    updateComplianceMetrics(data);
    updateComplianceTypesRanking(data.compliance_type_analysis);
    updateIssueSeverity(data.issue_category_analysis);
    updateComplianceDetails(data.compliance_details);
}

// 更新合规性分布图表
function updateComplianceDistributionChart(data) {
    if (!data || !data.status_distribution) return;

    const chart = charts.complianceDistribution;
    const statuses = Object.keys(data.status_distribution);
    const values = Object.values(data.status_distribution);

    chart.data.labels = statuses.map(status => getComplianceLabel(status));
    chart.data.datasets[0].data = values;
    chart.data.datasets[0].backgroundColor = statuses.map(status => getComplianceColor(status));

    chart.update();

    // 更新图例
    updateComplianceLegend(statuses, values);
}

// 更新合规性图例
function updateComplianceLegend(statuses, values) {
    const legend = document.getElementById('complianceLegend');
    if (!legend) return;

    const total = values.reduce((sum, val) => sum + val, 0);
    let html = '';

    statuses.forEach((status, index) => {
        const percentage = total > 0 ? ((values[index] / total) * 100).toFixed(1) : 0;
        html += `
            <div class="legend-item">
                <div class="legend-color" style="background-color: ${getComplianceColor(status)}"></div>
                <span>${getComplianceLabel(status)}: ${percentage}%</span>
            </div>
        `;
    });

    legend.innerHTML = html;
}

// 更新规范性类型图表
function updateComplianceTypesChart(data) {
    if (!data || !data.type_analysis) return;

    const chart = charts.complianceTypes;
    const types = Object.keys(data.type_analysis);
    const complianceRates = types.map(type => data.type_analysis[type].compliance_rate);

    chart.data.labels = types;
    chart.data.datasets[0].data = complianceRates;
    chart.data.datasets[0].backgroundColor = complianceRates.map(rate => {
        if (rate >= 80) return '#10b981';
        if (rate >= 60) return '#f59e0b';
        return '#ef4444';
    });

    chart.update();
}

// 更新问题类别图表
function updateIssueCategoriesChart(data) {
    if (!data || !data.top_issues) return;

    const chart = charts.issueCategories;
    const categories = data.top_issues;
    const severityScores = categories.map(category => {
        return data.category_analysis[category]?.severity_score || 0;
    });

    chart.data.labels = categories;
    chart.data.datasets[0].data = severityScores;
    chart.data.datasets[0].backgroundColor = severityScores.map(score => {
        if (score >= 80) return '#7c2d12';
        if (score >= 50) return '#ef4444';
        if (score >= 20) return '#f59e0b';
        return '#10b981';
    });

    chart.update();
}

// 更新置信度图表
function updateConfidenceCharts(data) {
    if (!data) return;

    // 更新统计图表
    const statsChart = charts.confidenceStats;
    statsChart.data.datasets[0].data = [
        data.average_confidence || 0,
        data.min_confidence || 0,
        data.max_confidence || 0
    ];
    statsChart.update();

    // 更新分布图表
    if (data.distribution) {
        const distChart = charts.confidenceDistribution;
        const categories = Object.keys(data.distribution);
        const values = Object.values(data.distribution);

        distChart.data.labels = categories;
        distChart.data.datasets[0].data = values;
        distChart.update();
    }

    // 更新分析内容
    updateConfidenceAnalysis(data);
}

// 更新合规性构成
function updateComplianceBreakdown(data) {
    const breakdown = document.getElementById('complianceBreakdown');
    if (!breakdown || !data || !data.status_distribution) return;

    const statuses = Object.keys(data.status_distribution);
    const total = data.total_count || 1;
    let html = '';

    statuses.forEach(status => {
        const count = data.status_distribution[status];
        const percentage = ((count / total) * 100).toFixed(1);
        const statusClass = getStatusClass(status);

        html += `
            <div class="d-flex justify-content-between align-items-center mb-2">
                <span>${getComplianceLabel(status)}</span>
                <div class="compliance-metrics">
                    <span class="compliance-rate ${statusClass}">${percentage}%</span>
                    <small class="text-muted">(${count})</small>
                </div>
            </div>
        `;
    });

    breakdown.innerHTML = html;
}

// 更新规范性指标
function updateComplianceMetrics(data) {
    const metrics = document.getElementById('complianceMetrics');
    if (!metrics || !data || !data.analysis_metadata) return;

    const metadata = data.analysis_metadata;
    const html = `
        <div class="compliance-item">
            <span class="compliance-name">分析准确率</span>
            <span class="compliance-rate high">${(metadata.accuracy_rate || 0).toFixed(1)}%</span>
        </div>
        <div class="compliance-item">
            <span class="compliance-name">完整性评分</span>
            <span class="compliance-rate medium">${(metadata.completeness_score || 0).toFixed(1)}%</span>
        </div>
        <div class="compliance-item">
            <span class="compliance-name">规范性评分</span>
            <span class="compliance-rate low">${(metadata.regularity_score || 0).toFixed(1)}%</span>
        </div>
    `;

    metrics.innerHTML = html;
}

// 更新规范性类型排行
function updateComplianceTypesRanking(data) {
    const ranking = document.getElementById('complianceTypesRanking');
    if (!ranking || !data || !data.type_analysis) return;

    const types = Object.keys(data.type_analysis);
    const sortedTypes = types.sort((a, b) => {
        return data.type_analysis[b].total_count - data.type_analysis[a].total_count;
    });

    let html = '';
    sortedTypes.slice(0, 10).forEach((type, index) => {
        const typeData = data.type_analysis[type];
        const complianceRate = typeData.compliance_rate;
        const rateClass = complianceRate >= 80 ? 'high' : complianceRate >= 60 ? 'medium' : 'low';

        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${index + 1}. ${type}</div>
                    <small class="text-muted">合规率: ${complianceRate.toFixed(1)}%</small>
                </div>
                <div class="compliance-metrics">
                    <span class="compliance-rate ${rateClass}">${complianceRate.toFixed(1)}%</span>
                    <small class="text-muted">(${typeData.total_count})</small>
                </div>
            </div>
        `;
    });

    ranking.innerHTML = html;
}

// 更新问题严重程度
function updateIssueSeverity(data) {
    const severity = document.getElementById('issueSeverity');
    if (!severity || !data || !data.severity_distribution) return;

    const severityDist = data.severity_distribution;
    let html = '';

    Object.entries(severityDist).forEach(([level, count]) => {
        const levelClass = level.toLowerCase().replace(' ', '-');
        html += `
            <div class="compliance-item">
                <span class="compliance-name">${level}</span>
                <span class="compliance-rate ${levelClass}">${count}</span>
            </div>
        `;
    });

    severity.innerHTML = html;

    // 更新高频问题
    updateFrequentIssues(data);
}

// 更新高频问题
function updateFrequentIssues(data) {
    const frequentIssues = document.getElementById('frequentIssues');
    if (!frequentIssues || !data || !data.top_issues) return;

    const issues = data.top_issues.slice(0, 5);
    let html = '';

    issues.forEach((issue, index) => {
        const issueData = data.category_analysis[issue];
        const severity = issueData?.severity_score || 0;
        const severityClass = severity >= 80 ? 'high' : severity >= 50 ? 'medium' : 'low';

        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${index + 1}. ${issue}</div>
                    <small class="text-muted">严重程度: ${severity.toFixed(1)}%</small>
                </div>
                <span class="compliance-rate ${severityClass}">${severity.toFixed(1)}%</span>
            </div>
        `;
    });

    frequentIssues.innerHTML = html;
}

// 更新置信度分析
function updateConfidenceAnalysis(data) {
    const analysis = document.getElementById('confidenceAnalysis');
    if (!analysis || !data) return;

    const avgConfidence = data.average_confidence || 0;
    const confidenceLevel = avgConfidence >= 0.8 ? '高' : avgConfidence >= 0.6 ? '中' : '低';
    const confidenceClass = avgConfidence >= 0.8 ? 'high' : avgConfidence >= 0.6 ? 'medium' : 'low';

    const html = `
        <div class="row">
            <div class="col-md-6">
                <div class="detail-card">
                    <div class="detail-header">
                        <div class="detail-title">置信度评估</div>
                        <div class="confidence-indicator ${confidenceClass}">
                            <i class="fas fa-chart-line"></i>
                            ${confidenceLevel}置信度
                        </div>
                    </div>
                    <div class="detail-content">
                        <div class="detail-section">
                            <div class="detail-label">平均置信度</div>
                            <div>${(avgConfidence * 100).toFixed(1)}%</div>
                        </div>
                        <div class="detail-section">
                            <div class="detail-label">置信度范围</div>
                            <div>${((data.min_confidence || 0) * 100).toFixed(1)}% - ${((data.max_confidence || 0) * 100).toFixed(1)}%</div>
                        </div>
                        <div class="detail-section">
                            <div class="detail-label">评估建议</div>
                            <div>${getConfidenceRecommendation(avgConfidence)}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="detail-card">
                    <div class="detail-header">
                        <div class="detail-title">数据质量</div>
                        <div class="confidence-indicator ${confidenceClass}">
                            <i class="fas fa-database"></i>
                            ${confidenceLevel}质量
                        </div>
                    </div>
                    <div class="detail-content">
                        <div class="detail-section">
                            <div class="detail-label">样本数量</div>
                            <div>${data.total_samples || 0}</div>
                        </div>
                        <div class="detail-section">
                            <div class="detail-label">有效样本</div>
                            <div>${data.valid_samples || 0}</div>
                        </div>
                        <div class="detail-section">
                            <div class="detail-label">质量评分</div>
                            <div>${(data.quality_score || 0).toFixed(1)}%</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    analysis.innerHTML = html;
}

// 获取置信度建议
function getConfidenceRecommendation(confidence) {
    if (confidence >= 0.8) {
        return '置信度较高，分析结果可靠，可以用于决策参考。';
    } else if (confidence >= 0.6) {
        return '置信度中等，分析结果有一定参考价值，建议结合其他信息使用。';
    } else {
        return '置信度较低，分析结果仅供参考，建议收集更多数据或改进分析方法。';
    }
}

// 更新规范性详情
function updateComplianceDetails(data) {
    const details = document.getElementById('complianceDetails');
    if (!details) return;

    if (!data || data.length === 0) {
        details.innerHTML = '<div class="empty-state"><i class="fas fa-inbox"></i><p>暂无规范性详情</p></div>';
        return;
    }

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = data.slice(startIndex, endIndex);

    let html = '';
    pageData.forEach(item => {
        const statusClass = getStatusClass(item.compliance_status);
        const statusLabel = getComplianceLabel(item.compliance_status);
        const confidenceClass = item.confidence >= 0.8 ? 'high' : item.confidence >= 0.6 ? 'medium' : 'low';

        html += `
            <div class="detail-card ${statusClass}">
                <div class="detail-header">
                    <div class="detail-title">${item.compliance_type || '未分类'}</div>
                    <div class="d-flex gap-2">
                        <span class="compliance-badge ${item.compliance_status}">${statusLabel}</span>
                        <span class="confidence-indicator ${confidenceClass}">
                            <i class="fas fa-brain"></i>
                            ${(item.confidence * 100).toFixed(1)}%
                        </span>
                    </div>
                </div>
                <div class="detail-content">
                    <div class="detail-section">
                        <div class="detail-label">问题类别</div>
                        <div>${item.issue_category || '无问题'}</div>
                    </div>
                    <div class="detail-section">
                        <div class="detail-label">原因分析</div>
                        <div>${item.reason || '无'}</div>
                    </div>
                    <div class="detail-section">
                        <div class="detail-label">改进建议</div>
                        <div>${item.suggestion || '无'}</div>
                    </div>
                    <div class="detail-meta">
                        <span><i class="fas fa-calendar"></i> ${item.created_at}</span>
                        <span><i class="fas fa-tag"></i> ${item.task_id || '未知任务'}</span>
                    </div>
                </div>
            </div>
        `;
    });

    details.innerHTML = html;
    updateDetailsPagination(data.length);
}

// 更新详情分页
function updateDetailsPagination(totalItems) {
    const pagination = document.getElementById('detailsPagination');
    const info = document.getElementById('detailsInfo');

    if (!pagination || !info) return;

    const totalPages = Math.ceil(totalItems / pageSize);
    const startIndex = (currentPage - 1) * pageSize + 1;
    const endIndex = Math.min(currentPage * pageSize, totalItems);

    // 更新信息
    info.textContent = `显示 ${startIndex}-${endIndex} 项，共 ${totalItems} 项`;

    // 生成分页按钮
    let paginationHtml = '';

    // 上一页
    paginationHtml += `
        <button class="btn btn-sm btn-outline-secondary" onclick="changePage(${currentPage - 1})"
                ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i>
        </button>
    `;

    // 页码
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        paginationHtml += `
            <button class="btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-outline-secondary'}"
                    onclick="changePage(${i})">
                ${i}
            </button>
        `;
    }

    // 下一页
    paginationHtml += `
        <button class="btn btn-sm btn-outline-secondary" onclick="changePage(${currentPage + 1})"
                ${currentPage === totalPages ? 'disabled' : ''}>
            <i class="fas fa-chevron-right"></i>
        </button>
    `;

    pagination.innerHTML = paginationHtml;
}

// 切换页面
function changePage(page) {
    const totalPages = Math.ceil((currentData?.compliance_details?.length || 0) / pageSize);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        updateComplianceDetails(currentData?.compliance_details || []);
    }
}

// 切换标签页
function switchTab(tabId) {
    // 更新标签按钮状态
    document.querySelectorAll('.custom-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabId}"]`).classList.add('active');

    // 显示对应内容
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.style.display = 'none';
    });

    const targetPane = document.getElementById(tabId);
    if (targetPane) {
        targetPane.style.display = 'block';
    }

    // 重新调整图表大小
    setTimeout(() => {
        Object.values(charts).forEach(chart => {
            if (chart.resize) chart.resize();
        });
    }, 100);
}

// 重置筛选条件
function resetFilters() {
    document.getElementById('taskSelect').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    document.getElementById('complianceStatus').value = '';
    document.getElementById('complianceType').value = '';
    document.getElementById('issueCategory').value = '';
    document.getElementById('minConfidence').value = '';

    setDefaultDates();
    loadAnalysis();
}

// 刷新图表
function refreshChart(chartType) {
    if (!currentData) return;

    switch (chartType) {
        case 'complianceDistribution':
            updateComplianceDistributionChart(currentData.compliance_distribution);
            break;
        case 'complianceTypes':
            updateComplianceTypesChart(currentData.compliance_type_analysis);
            break;
        case 'issueCategories':
            updateIssueCategoriesChart(currentData.issue_category_analysis);
            break;
        case 'confidenceStats':
        case 'confidenceDistribution':
            updateConfidenceCharts(currentData.confidence_analysis);
            break;
    }

    showNotification('图表已刷新', 'success');
}

// 下载图表
function downloadChart(chartType) {
    let chart;
    let filename;

    switch (chartType) {
        case 'complianceDistribution':
            chart = charts.complianceDistribution;
            filename = '合规性分布图表.png';
            break;
        case 'complianceTypes':
            chart = charts.complianceTypes;
            filename = '规范性类型图表.png';
            break;
        case 'issueCategories':
            chart = charts.issueCategories;
            filename = '问题类别图表.png';
            break;
        case 'confidenceStats':
            chart = charts.confidenceStats;
            filename = '置信度统计图表.png';
            break;
        case 'confidenceDistribution':
            chart = charts.confidenceDistribution;
            filename = '置信度分布图表.png';
            break;
    }

    if (chart) {
        const url = chart.toBase64Image();
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();

        showNotification('图表已下载', 'success');
    }
}

// 导出详情
function exportDetails() {
    if (!currentData || !currentData.compliance_details) {
        showNotification('没有数据可导出', 'warning');
        return;
    }

    const data = currentData.compliance_details;
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `规范性详情_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();

    showNotification('详情已导出', 'success');
}

// 转换为CSV
function convertToCSV(data) {
    const headers = ['规范性类型', '问题类别', '合规状态', '置信度', '原因', '建议', '创建时间'];
    const rows = data.map(item => [
        item.compliance_type || '',
        item.issue_category || '',
        getComplianceLabel(item.compliance_status),
        (item.confidence * 100).toFixed(1) + '%',
        item.reason || '',
        item.suggestion || '',
        item.created_at || ''
    ]);

    return [headers, ...rows].map(row =>
        row.map(field => `"${field}"`).join(',')
    ).join('\n');
}

// 刷新详情
function refreshDetails() {
    if (currentData) {
        updateComplianceDetails(currentData.compliance_details);
        showNotification('详情已刷新', 'success');
    }
}

// 显示加载状态
function showLoading(show) {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        if (show) {
            overlay.classList.add('active');
        } else {
            overlay.classList.remove('active');
        }
    }
}

// 显示错误信息
function showError(message) {
    showNotification(message, 'error');
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 显示空状态
function showEmptyState(message) {
    const tabContent = document.querySelector('.tab-content-custom');
    if (tabContent) {
        tabContent.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>${message}</p>
            </div>
        `;
    }
}

// 更新最后更新时间
function updateLastUpdateTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN');
    const element = document.getElementById('lastUpdate');
    if (element) {
        element.textContent = timeString;
    }
}

// 获取合规状态样式类
function getStatusClass(status) {
    const statusMap = {
        'compliant': 'compliant',
        'non_compliant': 'non-compliant',
        'partial': 'partial'
    };
    return statusMap[status] || 'partial';
}

// 获取合规状态标签
function getComplianceLabel(status) {
    const labelMap = {
        'compliant': '合规',
        'non_compliant': '不合规',
        'partial': '部分合规'
    };
    return labelMap[status] || status;
}

// 获取合规状态颜色
function getComplianceColor(status) {
    const colorMap = {
        'compliant': '#10b981',
        'non_compliant': '#ef4444',
        'partial': '#f59e0b'
    };
    return colorMap[status] || '#6b7280';
}

// 刷新Token
async function refreshToken() {
    const token = localStorage.getItem('auth_token');
    if (token) {
        // 这里可以添加Token刷新逻辑
        return token;
    }
    return null;
}
</script>
{% endblock %}